package com.pro.schedule.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pro.schedule.entity.EventType;
import com.pro.schedule.filter.ResultUtil;
import com.pro.schedule.mapper.EventMapper;
import com.pro.schedule.mapper.EventTypeChildMapper;
import com.pro.schedule.mapper.EventTypeMapper;
import com.pro.schedule.service.EventTypeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class EventTypeServiceImpl implements EventTypeService {
    @Resource
    ResultUtil resultUtil;
    @Resource
    EventTypeMapper eventTypeMapper;
    @Resource
    EventTypeChildMapper eventTypeChildMapper;
    @Resource
    EventMapper eventMapper;

    @Override
    public List<EventType> getEventTypeList(String token) {
        Long userId = resultUtil.getUserId(token);
        List<EventType> eventTypeList = eventTypeMapper.getEventTypeList(userId);
        for (EventType item : eventTypeList) {
            item.setUserId(0L);
        }
        return eventTypeList;
    }

    @Override
    public String saveOrUpdateEventType(String token, EventType eventType) throws Exception {
        Long userId = resultUtil.getUserId(token);
        eventType.setUserId(userId);
        QueryWrapper<EventType> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("event_type_label", eventType.getEventTypeLabel());
        if (eventType.getEventTypeId() == null) {
            int count = eventTypeMapper.selectCount(wrapper);
            if (count > 0) {
                return "该类型已存在";
            }
            int result = eventTypeMapper.insert(eventType);
            return resultUtil.getResult(result, "保存");
        } else {
            EventType oldEventType = eventTypeMapper.selectById(eventType.getEventTypeId());
            if (!Objects.equals(oldEventType.getEventTypeLabel(), eventType.getEventTypeLabel())) {
                int count = eventTypeMapper.selectCount(wrapper);
                if (count > 0) {
                    return "该类型已存在";
                }
            }
            int result = eventTypeMapper.updateById(eventType);
            return resultUtil.getResult(result, "修改");
        }
    }

    @Override
    public String deleteEventType(Integer eventTypeId) throws Exception {
        int result = eventTypeMapper.deleteById(eventTypeId);
        eventTypeChildMapper.deleteEventTypeChildByEventTypeId(eventTypeId);
        eventMapper.clearEventByEventTypeId(eventTypeId);
        return resultUtil.getResult(result, "删除");
    }


}
